<template>
  <div class="table-page-search-wrapper">
    <el-form
      :model="form"
      :inline="true"
      ref="form"
      label-width="100px"
      :rules="rules"
      class="editForm"
    >
      <el-row class="mb10" :gutter="24">
        <el-col :span="8" class="inlineWrap">
          <el-form-item label="供应商名称" prop="supplierName">
            <!-- <el-input
              :disabled="type === 'change' || type === 'edit' || type=== 'addType'"
              style="width: 100%"
              placeholder="请输入"
              v-model="form.supplierName"
            />-->
            <el-autocomplete
              :disabled="type === 'change' || type === 'edit' || type=== 'addType'"
              style="width: 100%"
              v-model="form.supplierName"
              :fetch-suggestions="(queryString, cb) => supplierQueryAsync(queryString, cb, true, 'supplier')"
              placeholder="请输入供应商名称"
              @select="value => supplierSelect(value, 'supplierName', 'supplierCode')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8" class="inlineWrap">
          <el-form-item label="供应商编码" class="mb10" prop="supplierCode">
            <supplier-modal @getSupplier="handleGetSupplier" ref="supplierModal" />
            <el-input
              style="width: 100%"
              :disabled="type === 'edit' || type === 'change' || type=== 'addType'"
              placeholder="请选择"
              @click.native="supplierFocus"
              v-model="form.supplierCode"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row class="mb10" :gutter="24">
        <el-col :span="8" class="inlineWrap">
          <el-form-item label="供应商类型" class="mb10" prop="supplierType">
            <el-select
              :disabled="type === 'change' || type === 'edit'"
              v-model="form.supplierType"
              placeholder="请选择"
              @change="typeChange"
              clearable
            >
              <el-option
                :value="item.value"
                v-for="(item,index) in typeData"
                :label="item.title"
                :key="index"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="inlineWrap">
          <el-form-item class="city-item" label="所属省份" prop="supplierProvince">
            <el-select
              :disabled="type=== 'addType'"
              v-model="form.supplierProvince"
              placeholder="请选择"
              clearable
              @change="provinceChange"
            >
              <el-option
                :value="item.value"
                v-for="item in provinceData"
                :key="item.value"
                :label="item.title ? item.title : item.label"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" class="inlineWrap">
          <el-form-item label="所属城市" prop="supplierCity">
            <el-select
              :disabled="type=== 'addType'"
              v-model="form.supplierCity"
              placeholder="请选择"
              clearable
            >
              <el-option
                :value="item.value"
                v-for="item in cityData"
                :key="item.title"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" class="mb10">
        <el-col :span="8" class="inlineWrap">
          <el-form-item class="city-item" label="性质" prop="supplierNature">
            <el-select
              :disabled="type=== 'addType'"
              v-model="form.supplierNature"
              placeholder="请选择"
              clearable
            >
              <el-option
                :value="item.value"
                v-for="item in natureData"
                :key="item.title"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="inlineWrap">
          <el-form-item class="city-item" label="规模" prop="supplierScale">
            <el-select
              :disabled="type=== 'addType'"
              v-model="form.supplierScale"
              placeholder="请选择"
              clearable
            >
              <el-option
                :value="item.value"
                v-for="item in scaleData"
                :key="item.title"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" class="inlineWrap">
          <el-form-item label="所属行业" prop="supplierIndustry">
            <el-select
              :disabled="type=== 'addType'"
              v-model="form.supplierIndustry"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in industryArr"
                :value="item.value"
                :key="item.value"
                :label="item.title"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="联系人名称" prop="username">
            <el-input v-model="form.username" placeholder="请输入联系人名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="联系人电话" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入联系人电话" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { getDicData } from '@/utils/util'
import { getDicTree } from '@/api/dictionary'
import { fuzzyQuery } from '@/api/assetsNew'
import { getSupplierCodeType, searchSupplier, saveSupplierDir, getSupplierCodeCount } from '@/api/supplier'
import SupplierModal from './supplierModal'

export default {
  components: {
    SupplierModal
  },
  data() {
    return {
      form: {},
      mdl: {},
      rules: {
        supplierCode: [{ required: true, message: '请输入供应商编码', trigger: 'blur' }],
        supplierName: [{ required: true, message: '请输入供应商名称', trigger: 'blur' }],
        supplierType: [{ required: true, message: '请选择供应商类型', trigger: 'blur' }],
        supplierProvince: [{ required: true, message: '请选择所属省份', trigger: 'blur' }],
        supplierCity: [{ required: true, message: '请选择所属城市', trigger: 'blur' }],
        supplierNature: [{ required: true, message: '请选择供应商性质', trigger: 'blur' }],
        supplierScale: [{ required: true, message: '请选择供应商规模', trigger: 'blur' }],
        supplierIndustry: [{ required: true, message: '请选择所属行业', trigger: 'blur' }],
        username: [{ required: true, message: '请输入联系人名称', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
          {
            message: '电话号码格式不正确',
            pattern: /^1[3456789]\d{9}$/,
            trigger: 'blur'
          }
        ]
      },
      type: '',
      typeData: [], // 类型
      natureData: [], // 性质
      scaleData: [], //规模
      provinceData: [], // 省份
      cityData: [], // 城市
      industryArr: [], // 行业
      selectValue: ''
    }
  },
  async created() {
    this.provinceData = getDicData('001', '001001')
    this.typeData = getDicData('002', '002001')
    this.scaleData = getDicData('002', '002004')
    this.natureData = getDicData('002', '002002')
    this.industryArr = getDicData('002', '002003')
  },
  methods: {
    supplierFilter(queryString) {
      return state => {
        // console.log('state', state)
        return state.supplier.indexOf(queryString) >= 0
      }
    },
    async supplierQueryAsync(queryString, cb, bool, mode) {
      console.log('bool', bool)
      if (mode === 'supplier') {
        this.$set(this.form, 'supplierCode', null)
      } else {
        this.$set(this.form, 'factoryCode', null)
      }
      queryString = queryString === undefined ? null : queryString
      let results = []
      if (queryString) {
        console.log('queryString', queryString)
        let res = ''
        if (bool) {
          //   res = await supplierFuzzyQuery({ supplierName: queryString })
          res = await searchSupplier({ supplier: queryString })
        } else {
          res = await fuzzyQuery({ assetsName: queryString })
        }
        var supplier = res.data
        if (queryString) {
          if (bool) {
            // 过滤供应商
            results = supplier.filter(this.supplierFilter(queryString))
          } else {
            results = supplier.filter(this.nameFilter(queryString))
          }
        } else {
          results = supplier
        }
        if (bool) {
          results.map(v => {
            v.value = v.supplier
          })
        } else {
          results.map(v => {
            v.value = v.assetsName
          })
        }
        // console.log('results', results)
        if (results.length === 0) {
          if (bool) {
            // 供应商
            results.push({
              value: `新增[${queryString}]`,
              supplier: queryString,
              supplierId: '-1'
            })
          }
        }

        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 1000 * Math.random())
      } else {
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 300 * Math.random())
      }
    },
    async supplierSelect(value, key, code) {
      //   console.log('supplierSelect', value, key)
      let next = false
      if (value.supplierId === '-1') {
        const res = await saveSupplierDir({ supplier: value.supplier })
        console.log('res', res)
        if (res.state === '000000') {
          this.$set(this.form, 'supplierName', value.supplier)
          this.$set(this.form, 'supplierCode', res.data)
        }
      } else {
        const res = await getSupplierCodeCount({ supplierCode: this.selectedRows[0].id })
        console.log('res', res)
        if (res.state === '000000' && res.data) {
          next = true
          this.$set(this.form, code, value.supplierId)
        } else {
          this.$message.error('该供应商已存在，请选择其他供应商')
        }
      }
      if (next) {
        this.$set(this.form, key, value.supplier)
      }
      console.log('form', this.form)
    },
    handleGetSupplier(arr) {
      const obj = arr[0]
      this.$nextTick(() => {
        this.$set(this.form, 'supplierCode', obj.id)
        this.$set(this.form, 'supplierName', obj.name)
      })
    },
    typeChange(val) {
      console.log('val', val)
    },
    supplierFocus() {
      if (this.type === 'edit' || this.type === 'change' || this.type === 'addType') {
        return false
      } else {
        this.$nextTick(() => {
          this.$refs.supplierModal.edit()
        })
      }
    },
    reset() {
      this.$refs.form.resetFields()
    },
    async getDicTree(id) {
      const res = await getDicTree(id)
      if (res.state === '000000') {
        return res.data
      }
    },
    async provinceChange(value) {
      console.log('value', value)
      this.cityData = await this.getDicTree(value)
      this.$nextTick(() => {
        this.$set(this.form, 'supplierCity', null)
      })
    },
    getFormData() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$emit('sendData', this.form, 1)
        } else {
          this.$emit('notSubmit', false, 1)
        }
      })
    },
    async edit(type, obj) {
      // type 为 变更，编辑，新增，新增类型，详情
      this.type = type
      console.log('this.typeData', this.typeData)
      console.log('obj', obj)
      this.selectValue = obj.supplierCode
      this.mdl = Object.assign({}, obj)
      this.form = Object.assign({}, obj)
      if (this.type !== 'add') {
        this.cityData = await this.getDicTree(this.form.supplierProvince)
      }
      if (type === 'addType') {
        const res = await getSupplierCodeType({ supplierCode: obj.supplierCode })
        let arr = []
        if (res.data.length > 0) {
          res.data.map(v => {
            arr = this.typeData.filter(a => a.value !== v)
          })
          this.typeData = [...arr]
        }
        this.$set(this.form, 'supplierType', null)
      }
    }
  }
}
</script>

<style scoped>
.editForm >>> .city-item .ant-form-item-label {
  width: 103px;
}
</style>

<style lang="less">
.inlineWrap {
  .ant-form-item {
    display: flex;
    margin-right: 0;

    .ant-form-item-control-wrapper {
      flex: 1 1;
      display: inline-block;
      vertical-align: middle;
    }

    > .ant-form-item-label {
      line-height: 32px;
      padding-right: 8px;
      width: auto;
    }
    .ant-form-item-control {
      height: 32px;
      line-height: 32px;
    }
  }
}
</style>